// 存储回忆数据
let memories = [];
let currentYear = null;
let currentMonth = null;

// 年份范围
const START_YEAR = 2025;
const END_YEAR = 2120;
const VISIBLE_YEARS = 5;

// DOM元素
const memoryContainer = document.querySelector('.memory-container');
const imageViewModal = document.getElementById('imageViewModal');
const yearsContainer = document.querySelector('.years');
const monthButtons = document.querySelectorAll('.month-btn');
const prevButton = document.querySelector('.nav-prev');
const nextButton = document.querySelector('.nav-next');
const yearInput = document.getElementById('yearInput');
const yearJumpBtn = document.getElementById('yearJumpBtn');

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    console.log('页面加载开始');
    
    // 检查 timelineData 是否存在
    if (typeof timelineData === 'undefined' || !timelineData.timeline) {
        console.error('无法加载数据，timelineData 未定义或格式不正确');
        showError('数据加载失败，请检查 data.js 文件');
        return;
    }
    
    // 从全局变量 timelineData 中获取数据
    memories = timelineData.timeline;
    console.log('加载的数据:', memories);

    // 生成年份按钮
    generateInitialYearButtons();
    initializeNavigation();

    // 设置初始年月为数据中的第一条记录的时间
    if (memories.length > 0) {
        const firstMemory = memories[0];
        const date = new Date(firstMemory.date);
        currentYear = date.getFullYear();
        currentMonth = date.getMonth() + 1;
        console.log('设置初始年月:', currentYear, currentMonth);
        updateYearButtons(currentYear);
    } else {
        console.log('没有找到任何回忆数据');
        currentYear = START_YEAR;
        currentMonth = 1;
    }
    
    updateActiveButtons();
    displayMemoriesForCurrentMonth();
    initializeImageViewer();
    console.log('页面初始化完成');
});

// 加载回忆数据
async function loadMemories() {
    try {
        // 使用 data.js 中的数据
        memories = timelineData.timeline;
        console.log('Loaded memories:', memories);
        
        // 设置初始年份和月份为第一个记录的日期
        if (memories.length > 0) {
            const firstMemory = memories[0];
            const [year, month] = firstMemory.date.split('-').map(Number);
            currentYear = year;
            currentMonth = month;
            console.log('Initial year and month set to:', currentYear, currentMonth);
        }
    } catch (error) {
        console.error('Error loading memories:', error);
    }
}

// 生成初始年份按钮
function generateInitialYearButtons() {
    const startYear = START_YEAR;
    for (let i = 0; i < VISIBLE_YEARS; i++) {
        const year = startYear + i;
        const button = createYearButton(year);
        yearsContainer.appendChild(button);
    }
}

// 创建年份按钮
function createYearButton(year) {
    const button = document.createElement('button');
    button.className = 'year-btn';
    button.dataset.year = year;
    button.innerHTML = `
        <span class="year-text">${year}</span>
        <span class="year-dot"></span>
    `;
    button.addEventListener('click', () => {
        currentYear = year;
        updateYearButtons(year);
        updateActiveButtons();
        displayMemoriesForCurrentMonth();
    });
    return button;
}

// 更新年份按钮
function updateYearButtons(centerYear) {
    yearsContainer.innerHTML = '';
    const halfVisible = Math.floor(VISIBLE_YEARS / 2);
    let startYear = centerYear - halfVisible;
    if (startYear < START_YEAR) {
        startYear = START_YEAR;
    } else if (startYear > END_YEAR - VISIBLE_YEARS + 1) {
        startYear = END_YEAR - VISIBLE_YEARS + 1;
    }
    for (let i = 0; i < VISIBLE_YEARS; i++) {
        const year = startYear + i;
        const button = createYearButton(year);
        if (year === currentYear) {
            button.classList.add('active');
        }
        yearsContainer.appendChild(button);
    }
    // 更新导航按钮状态
    prevButton.disabled = startYear <= START_YEAR;
    nextButton.disabled = startYear + VISIBLE_YEARS > END_YEAR;
}

// 初始化导航
function initializeNavigation() {
    prevButton.addEventListener('click', () => {
        const firstYear = parseInt(yearsContainer.firstElementChild.dataset.year);
        if (firstYear > START_YEAR) {
            updateYearButtons(firstYear - 1);
        }
    });
    nextButton.addEventListener('click', () => {
        const lastYear = parseInt(yearsContainer.lastElementChild.dataset.year);
        if (lastYear < END_YEAR) {
            updateYearButtons(lastYear + 1);
        }
    });
    yearJumpBtn.addEventListener('click', handleYearJump);
    yearInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            handleYearJump();
        }
    });
}

// 处理年份跳转
function handleYearJump() {
    const year = parseInt(yearInput.value);
    if (year >= START_YEAR && year <= END_YEAR) {
        currentYear = year;
        updateYearButtons(year);
        updateActiveButtons();
        displayMemoriesForCurrentMonth();
        yearInput.value = '';
    } else {
        alert(`请输入${START_YEAR}-${END_YEAR}之间的年份`);
    }
}

// 更新活动按钮状态
function updateActiveButtons() {
    if (!currentYear || !currentMonth) return;
    document.querySelectorAll('.year-btn').forEach(btn => {
        const year = parseInt(btn.dataset.year);
        btn.classList.toggle('active', year === currentYear);
    });
    monthButtons.forEach(btn => {
        const month = parseInt(btn.dataset.month);
        btn.classList.toggle('active', month === currentMonth);
    });
}

// 显示当前月份的回忆
function displayMemoriesForCurrentMonth() {
    if (!currentYear || !currentMonth) return;
    const filteredMemories = memories.filter(memory => {
        const date = new Date(memory.date);
        const memoryYear = date.getFullYear();
        const memoryMonth = date.getMonth() + 1;
        return memoryYear === currentYear && memoryMonth === currentMonth;
    });
    displayMemories(filteredMemories);
}

// 显示回忆列表
function displayMemories(memories) {
    memoryContainer.innerHTML = '';
    if (!memories || memories.length === 0) {
        showEmptyState();
        return;
    }
    memories.forEach(memory => {
        const card = createMemoryCard(memory);
        memoryContainer.appendChild(card);
        requestAnimationFrame(() => {
            card.style.opacity = '1';
            card.style.transform = 'translateY(0)';
        });
    });
    // 重新绑定图片查看器事件
    initializeImageViewer();
}

// 初始化图片查看器
function initializeImageViewer() {
    const imageElements = document.querySelectorAll('.memory-card img');
    const closeButton = document.querySelector('#imageViewModal .close');
    const viewedImage = document.getElementById('viewedImage');

    imageElements.forEach(img => {
        img.addEventListener('click', () => {
            imageViewModal.style.display = 'block';
            imageViewModal.classList.add('active'); // 确保添加 active 类
            viewedImage.src = img.src;
            // 设置图片最大宽度和高度
            viewedImage.style.maxWidth = '80vw';
            viewedImage.style.maxHeight = '80vh';
            // 水平垂直居中
            viewedImage.style.position = 'absolute';
            viewedImage.style.top = '50%';
            viewedImage.style.left = '50%';
            viewedImage.style.transform = 'translate(-50%, -50%)';
            document.body.style.overflow = 'hidden';
        });
    });

    if (closeButton) {
        closeButton.addEventListener('click', () => {
            imageViewModal.style.display = 'none';
            imageViewModal.classList.remove('active'); // 确保移除 active 类
            document.body.style.overflow = 'auto';
        });
    }
}

// 显示图片
function showImage(imageSrc) {
    const viewedImage = document.getElementById('viewedImage');
    viewedImage.src = imageSrc;
    // 设置图片最大宽度和高度
    viewedImage.style.maxWidth = '80vw';
    viewedImage.style.maxHeight = '80vh';
    // 水平垂直居中
    viewedImage.style.position = 'absolute';
    viewedImage.style.top = '50%';
    viewedImage.style.left = '50%';
    viewedImage.style.transform = 'translate(-50%, -50%)';
    imageViewModal.style.display = 'block';
    imageViewModal.classList.add('active');
    document.body.style.overflow = 'hidden';
}

// 创建回忆卡片
function createMemoryCard(memory) {
    const card = document.createElement('div');
    card.className = 'memory-card';
    card.style.opacity = '0';
    card.style.transform = 'translateY(20px)';
    const date = new Date(memory.date);
    const formattedDate = date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
    });
    const content = `
        <button class="view-desc-btn">查看</button>
        ${memory.image && !memory.image.endsWith('.mp4') ? `<img src="${memory.image}" alt="${memory.title}" loading="lazy" onclick="showImage('${memory.image}')">` : ''}
        ${memory.image && memory.image.endsWith('.mp4') || memory.video ? `<video src="${memory.image || memory.video}" controls onclick="showVideo('${memory.image || memory.video}')"></video>` : ''}
        <h3>${memory.title}</h3>
        <p>${memory.description}</p>
        <div class="date">${formattedDate}</div>
        ${memory.image ? `<button class="download-btn" data-img="${memory.image}">下载</button>` : ''}
    `;
    card.innerHTML = content;

    // 添加查看详情按钮事件监听
    const viewDescBtn = card.querySelector('.view-desc-btn');
    if (viewDescBtn) {
        viewDescBtn.addEventListener('click', () => {
            let modal = document.getElementById('desc-modal');
            if (!modal) {
                modal = document.createElement('div');
                modal.id = 'desc-modal';
                modal.className = 'desc-modal';
                modal.innerHTML = `
                    <div class="modal-content">
                        <span class="close-btn">&times;</span>
                        <p id="modal-description"></p>
                    </div>
                `;
                document.body.appendChild(modal);

                // 添加关闭模态框事件监听
                const closeBtn = modal.querySelector('.close-btn');
                if (closeBtn) {
                    closeBtn.addEventListener('click', () => {
                        modal.style.display = 'none';
                    });
                }
            }
            // 更新模态框内容
            const modalDescription = modal.querySelector('#modal-description');
            if (modalDescription) {
                modalDescription.textContent = memory.description;
            }
            modal.style.display = 'block';
        });
    }

    // 强制下载逻辑
    const downloadBtn = card.querySelector('.download-btn');
    if (downloadBtn) {
        downloadBtn.addEventListener('click', function(e) {
            e.stopPropagation();
            const url = downloadBtn.getAttribute('data-img');
            const fileName = url.split('/').pop();
            fetch(url)
                .then(resp => resp.blob())
                .then(blob => {
                    const a = document.createElement('a');
                    a.href = URL.createObjectURL(blob);
                    a.download = fileName;
                    document.body.appendChild(a);
                    a.click();
                    a.remove();
                    URL.revokeObjectURL(a.href);
                });
        });
    }

    return card;
}

// 显示空状态
function showEmptyState() {
    memoryContainer.innerHTML = `
        <div class="empty-state">
            <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
                <polyline points="17 8 12 3 7 8"/>
                <line x1="12" y1="3" x2="12" y2="15"/>
            </svg>
            <p>这个月份还没有回忆呢~</p>
        </div>
    `;
}

// 显示错误信息
function showError(message) {
    memoryContainer.innerHTML = `
        <div class="error-state">
            <svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="12" cy="12" r="10"/>
                <line x1="12" y1="8" x2="12" y2="12"/>
                <line x1="12" y1="16" x2="12.01" y2="16"/>
            </svg>
            <p>${message}</p>
        </div>
    `;
}

// 月份按钮点击事件
monthButtons.forEach(btn => {
    btn.addEventListener('click', () => {
        currentMonth = parseInt(btn.dataset.month);
        updateActiveButtons();
        displayMemoriesForCurrentMonth();
    });
});

// 添加滚动动画
const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            entry.target.style.opacity = '1';
            entry.target.style.transform = 'translateY(0)';
        }
    });
}, {
    threshold: 0.1
});

document.querySelectorAll('.memory-card').forEach(card => {
    observer.observe(card);
});
